<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Cate;
use App\Models\Conf;
use App\Models\Nav;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    const DATA_NUMBER=6;//数据条数
    /**
     * 首页的数据输出
     */
    public function index()
    {

        $data['words']=$this->words();
        $data['articleEssence']=$this->articleEssence();
        $data['articleNew']=$this->articleNew();
        $data['articleClick']=$this->articleClickNow();
        return ['status_code'=>200,'message'=>'数据获取成功','result'=>$data];

    }

    /**
     * 点击排行和最新文章
     */
    public function articleNewAndClick()
    {
        $data['articleNew']=$this->articleNew();
        $data['articleClick']=$this->articleClickNow();
        return ['status_code'=>200,'message'=>'数据获取成功','result'=>$data];
    }

    /**
     * 顶部链接
     */
    public function navs()
    {

        $data =Nav::orderBy('order','asc')->get();
        return ['status_code'=>200,'message'=>'数据获取成功','result'=>$data];
    }

    /**
     * banner上的文字
     */
    private function words()
    {

        return '  <p>游手好闲会使人心智生锈。</p>       <p>觉得自己做的到和不做的到，其实只在一念之间。</p>       <p>人在旅途，难免会遇到荆棘和坎坷，但风雨过后，一定会有美丽的彩虹。</p>';

    }

    /**
     * 精华文章
     */
    private function articleEssence()
    {
        return Article::where([['show_status',1],['essence',1]])->select('id','title','thumb')
            ->orderBy('id','desc')->limit(self::DATA_NUMBER)->get();

    }

    /**
     * 推荐文章
     *  alter table blog_article add fulltext index ix_ft_title(title) with parser ngram;
     */
    public function articleRecommend()
    {


        if($search=request()->search){
            //搜索，全部显示
            $limit=3000;
            $whereRaw="MATCH (title) AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)";
        }else{
            $whereRaw='1=1';
            $limit=self::DATA_NUMBER;
        }


        $data=Article::with('cate:id,name')
            ->whereRaw($whereRaw)
            ->where('show_status',1)
            ->orderBy('id','desc')
            ->select(['id','title','thumb','created_at','author','description','cate_id'])
            ->paginate($limit);


        return ['status_code'=>200,'message'=>'数据获取成功','result'=>$data];
    }

    /**
     * 最新文章
     */
    private function articleNew()
    {
        return Article::with('cate:id,thumb')->where('show_status',1)->select('id','title')
            ->orderBy('id','desc')->limit(self::DATA_NUMBER)->get();
    }


    /**
     * 功能：获取最新的点击排行
     */
    public function articleClickNow()
    {
        return Article::where('show_status',1)->select('id','title')
            ->orderBy('view_times','desc')->limit(self::DATA_NUMBER)->get();
    }


}
